<template>
  <div class="main">
    <div>
      <div class="title">欢迎注册yx聊天室</div>
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="username"
            name="username"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="password"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
        </van-cell-group>
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            注册
          </van-button>
        </div>
      </van-form>
      <van-dialog
        v-model:show="show"
        title="温馨提示"
        message="注册账号成功，即将跳转到聊天页面"
        @confirm="onOk"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { goRegister, goLogin } from "@/api/user";
import { showToast } from "vant";
import { useRouter } from "vue-router";

const username = ref("");
const password = ref("");
const show = ref(false);
const router = useRouter();
let token = "";
let user = {};
const onSubmit = (values) => {
  goRegister({
    username: values.username,
    password: values.password,
  }).then((res) => {
    if (res.code === 200) {
      goToLogin(values);
    } else {
      showToast(res.message);
    }
  });
};
const onOk = () => {
  show.value = false;
  localStorage.setItem("isLogin", "1");
  localStorage.setItem("token", token);
  localStorage.setItem("userInfo", JSON.stringify(user));
  router.push("/");
  setTimeout(() => {
    window.location.reload();
  }, 100);
};

const goToLogin = (values) => {
  goLogin({
    username: values.username,
    password: values.password,
  }).then((res) => {
    if (res.code === 200) {
      token = res.data.token;
      user = res.data.user;
      show.value = true;
    } else {
      showFailToast(res.message);
    }
  });
};
</script>

<style scoped lang="scss">
.main {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background: url("@/assets/bg.jpg") no-repeat;
  background-size: cover;
  .title {
    width: 100vw;
    text-align: center;
    font-size: 18px;
    color: #fff;
    font-weight: bold;
    margin-bottom: 15px;
  }
}
</style>
